package com.richie696.account.service.impl;

import com.richie696.account.dao.AccountDAO;
import com.richie696.account.domain.Account;
import com.richie696.account.json.ExecuteResult;
import com.richie696.account.model.AccountRequestModel;
import com.richie696.account.model.AccountResponseModel;
import com.richie696.account.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDAO accountDAO;

    @Override
    public ExecuteResult<AccountResponseModel> doTransferProcess(AccountRequestModel model) {
        if (Objects.isNull(model) || model.isInvalid()) {
            return ExecuteResult.getErrorResult("转账执行失败，请重试。");
        }
        Account fromAccount = accountDAO.findById(model.getFromCardNo()).orElseThrow();
        Account toAccount = accountDAO.findById(model.getToCardNo()).orElseThrow();
        double transferMoney = model.getMoney();
        ExecuteResult<AccountResponseModel> result = doTransferProcessBefore(fromAccount, toAccount, transferMoney);
        if (!result.isSuccess()) {
            return result;
        }
        accountDAO.saveAll(List.of(fromAccount, toAccount));
        return result.setData(new AccountResponseModel(fromAccount.getMoney().longValue(), toAccount.getMoney().longValue()));
    }

    private ExecuteResult<AccountResponseModel> doTransferProcessBefore(
            Account fromAccount, Account toAccount, double transferMoney) {
        if (Objects.isNull(fromAccount)) {
            return ExecuteResult.getErrorResult("指定的转出方账户不存在。");
        }
        if (Objects.isNull(toAccount)) {
            return ExecuteResult.getErrorResult("指定的转入方账户不存在。");
        }
        if (transferMoney < 0) {
            return ExecuteResult.getErrorResult("转账金额有误，请重试。");
        }
        double fromMoney = fromAccount.getMoney() - transferMoney;
        if (fromMoney < 0) {
            return ExecuteResult.getErrorResult("指定的转出方账户余额不足。");
        }
        fromAccount.setMoney(fromMoney);
        toAccount.setMoney(toAccount.getMoney() + transferMoney);
        return ExecuteResult.getSuccess();
    }

}
